package vip.george.bean.register;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import vip.george.bean.service.impl.BookServiceImpl1;
import vip.george.bean.service.impl.BookServiceImpl2;

import java.util.Arrays;


/**
 * 自定义注册类
 * 演示如何在BeanDefinitionRegistryPostProcessor中添加和删除Bean定义
 */
public class MyRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {


    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {


        System.out.println("当前已注册的Bean定义: " + Arrays.toString(beanDefinitionRegistry.getBeanDefinitionNames()));
        // 删除指定名称的Bean定义示例
        String beanNameToRemove = "yello-dog";
        if (beanDefinitionRegistry.containsBeanDefinition(beanNameToRemove)) {
            beanDefinitionRegistry.removeBeanDefinition(beanNameToRemove);
            System.out.println("已删除Bean定义: " + beanNameToRemove);
        } else {
            System.out.println("未找到Bean定义: " + beanNameToRemove);
        }
        
        // 注册新的Bean定义
        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(BookServiceImpl2.class).getBeanDefinition();
        // 会覆盖之前的同名Bean定义
        beanDefinitionRegistry.registerBeanDefinition("book", beanDefinition);
        System.out.println("已注册新的Bean定义: book");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}